package util;

import android.app.Activity;
import android.util.Base64;
import android.util.Log;
import android.widget.TextView;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import com.gonfre.quientelo.MainActivity;
import com.gonfre.quientelo.R;

/**
 * Created by Tecnocom on 12/17/2014.
 */
public class Request {
    Activity m;

    public Request(Activity m){
        this.m = m;
    }

    public Response xLogin(String email, String pass){
        // MD5
        pass = hash(pass);
        String params = getConcatenatedParams(email, pass);
        Response res = new Response();
        res = getServerData(1, params);
        return res;
    }

    public Response xRegisterSeller(String name, String phone, String email, String pass, Integer location, String categories){
        // MD5
        pass = hash(pass);
        String params = getConcatenatedParams(name, phone, email, pass, location.toString(), categories);
        Response res = new Response();
        res = getServerData(2, params);
        return res;
    }

    public Response xRegistrerPurchaser(String name, String phone, String email, String pass, Integer country){
        // MD5
        pass = hash(pass);
        String params = getConcatenatedParams(name, phone, email, pass, country.toString());
        Response res = new Response();
        res = getServerData(3, params);
        return res;
    }

    public Response xGetDescriptionList(String text){
        String params = getConcatenatedParams(text);
        Response res = new Response();
        res = getServerData(4, params);
        return res;
    }

    public Response xGetLocationList(String text){
        String params = getConcatenatedParams(text);
        Response res = new Response();
        res = getServerData(5, params);
        return res;
    }

    public Response xGetCategoryList(String text){
        String params = getConcatenatedParams(text);
        Response res = new Response();
        res = getServerData(6, params);
        return res;
    }

    public Response xGetCountryList(){
        Response res = new Response();
        res = getServerData(7, "");
        return res;
    }

    public Response xRequestPrice(String description, Integer category, String locations, String only_photo){
        String params = getConcatenatedParams(description, category.toString(), locations, only_photo);
        Response res = new Response();
        res = getServerData(8, params);
        return res;
    }

    public Response xGetReceivedPriceList(Integer product, String only_photo, Integer price_min, Integer price_max, String locations){
        String params = getConcatenatedParams(product.toString(), only_photo, price_min.toString(), price_max.toString(), locations);
        Response res = new Response();
        res = getServerData(9, params);
        return res;
    }

    private String getConcatenatedParams(String... p){
        String res = "<NULL>";
        Integer len = p.length;

        try {
            for(int i=0; i<len; i++){
                if(i==0)
                    res = p[i];
                else
                    res = res+"||"+p[i];
            }
            Log.i("Trace 'getConcatenatedParams', res: ", res);
        }catch (Exception e){
            e.printStackTrace();
            Log.i("Parse Exception 'xRequest': ", e.toString());
            res = "<NULL>";
        }
        return res;
    }

    private String getEncodeBase64(String str){
        byte[] data = new byte[0];
        String base64 = "NULL";
        try {
            data = str.getBytes("UTF-8");
            base64 = Base64.encodeToString(data, Base64.DEFAULT);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            Log.i("Parse Exception 'getEncodeBase64': ", e.toString());
        }

        return base64;
    }

    public static String hash(String string) {
        try {
            //.s. Create MD5 Hash
            MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
            digest.update(string.getBytes());
            byte messageDigest[] = digest.digest();

            //.s. Create Hex String
            StringBuffer hexString = new StringBuffer();
            for (int i=0; i<messageDigest.length; i++)
                hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return string.replaceAll("[.:/,%?#&=]","");
    }

    private String xRequest(String url, String v){
        String response = null;
        try {
            httpHandler handler = new httpHandler();
            response = handler.post(url, v);
        }catch(Exception e){
            e.printStackTrace();
            Log.i("Parse Exception 'xRequest': ", e.toString());
            response = "<ERROR>";
        }
        return response;
    }

    private String getPetitionHeader(Integer petition_type){
        String res = "<NULL>";
        try {

            res = m.getString(R.string.app_version) + "||" + "keykeykey" + "||" + petition_type + "||" + "es";
        }catch (Exception e){
            e.printStackTrace();
            Log.i("Parse Exception 'xRequest': ", e.toString());
            res = "<NULL>";
        }
        return res;
    }

    public Response getServerData(Integer petition_type, String params){
        // Objeto Response
        Response response = new Response();

        // Se obtiene los datos del Header a enviar
        String v =  getPetitionHeader(petition_type);

        // Si se envían parametros adicionales al header, se concatena a la peticion v
        if(params.compareTo("")!=0){
            v = v+"||"+params;
        }
        Log.i("Trace 'getServerData', v: ", v);

        // Se obtiene el string del request en Base64
        String vBase64 = getEncodeBase64(v);
        Log.i("Trace 'getServerData', vBase64: ", vBase64);

        // Se hace la petición al servidor
        String responseStr = xRequest(m.getString(R.string.request_url), vBase64);
        response = new Response(responseStr);
        Log.i("Trace 'getServerData', responseStr: ", responseStr);

        return response;
    }
}
